package com.trg.flex.dp
{
	import com.trg.flex.search.Search;
	
	import mx.collections.Sort;
	import mx.events.PropertyChangeEvent;
	
	public class LocalSearchDataProvider extends LocalDataProvider
	{
		public function LocalSearchDataProvider(source:* = null, search:Search = null)
		{
			super(source);
			this.search = search;
		}
		
		protected var _search:Search;
		
		public function set search(value:Search):void {
			if (_search != null) {
				_search.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, searchChangeListener);
			}			
			_search = value;
			if (_search != null) {
				_search.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, searchChangeListener);
				sort = _search.sort;
				page = _search.page;
				resultsPerPage = _search.maxResults;
			}
		}
		public function get search():Search {
			return _search;
		}
		
		override protected function refreshInternal(refreshCollection:Boolean):void {
			if (_search != null) {
				_sort = _search.sort;
				_filterFunction = _search.filterFunction;
			}
			super.refreshInternal(refreshCollection);
		}

		protected var processingChange:Boolean;
		protected function searchChangeListener(event:PropertyChangeEvent):void {
			processingChange = true;
			switch (event.property) {
				case "sort": sort = _search.sort; break;
				case "page": page = _search.page; break;
				case "maxResults": resultsPerPage = _search.maxResults; break;
			}
			processingChange = false;
		}
		
		override public function set sort(value:Sort):void {
			super.sort = value;
			if (!processingChange && _search != null) _search.sort = _sort;
		}
		
		override public function set page(value:int):void {
			super.page = value;
			if (!processingChange && _search != null) _search.page = _page;
		}
		
		override public function set resultsPerPage(value:int):void {
			super.resultsPerPage = value;
			if (!processingChange && _search != null) _search.maxResults = _resultsPerPage;
		}
	}
}